<template>
  <div class="app-container">

    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system/auth/addMenu']">新增</el-button>

    <el-table
        v-loading="loading"
        :data="menuList"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="title" label="分类名称" :show-overflow-tooltip="true" width="360"></el-table-column>
      <el-table-column prop="name" label="分类编码" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="icon" label="图标" align="center" width="100">
        <template slot-scope="scope">
          <svg-icon :icon-class="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="weigh" label="排序" width="60"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" width="80"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini"  v-if="row.id>102"
                     icon="el-icon-edit"
                     @click="handleUpdate(row)"
                     v-hasPermi="['system/auth/editMenu']"
          >修改</el-button>

          <el-button
              size="mini"
              icon="el-icon-plus"
              @click="handleAdd(row)"
              v-hasPermi="['system/auth/addMenu']"
          >新增</el-button>

          <el-button  v-if="row.id>102"
                      size="mini"
                      icon="el-icon-delete"
                      @click="handleDelete(row)"
                      v-hasPermi="['system/auth/deleteMenu']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="上级菜单">
              <el-cascader
                  :options="menuData"
                  :props="{ label: 'title',value: 'id',checkStrictly: true,emitPath: false }"
                  placeholder="请选择上级菜单"
                  clearable
                  class="w100"
                  v-model="ruleForm.pid"
              >
                <template #default="{ node, data }">
                  <span>{{ data.title }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item v-if="form.menuType != '2'"  label="菜单图标">
              <IconSelector placeholder="请输入菜单图标" v-model="form.icon" type="all" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="分类编码" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类编码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item v-if="form.menuType != '2'" label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio
                    v-for="dict in visibleOptions.values"
                    :key="dict.key"
                    :label="dict.key"
                >{{dict.value}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType != '2'" label="分类状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in statusOptions.values"
                    :key="dict.key"
                    :label="dict.key"
                >{{dict.value}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {ref, toRefs, reactive, onBeforeMount, defineComponent, getCurrentInstance, unref} from 'vue';
import {getMenuParams, getMenuInfo, updateMenu, getMenuList} from "/@/api/system/menu";
import XEUtils from 'xe-utils'
import IconSelector from '/@/components/iconSelector/index.vue';
import { listCateMenu ,getCategory,addMenu} from '/@/api/linkoo/category'
import { mapState } from 'vuex'


export default defineComponent({
  name: "Category",
  components: { IconSelector},
  setup(props,{emit}) {
    const state = reactive({
      // 遮罩层
      loading: true,
      // 分类表格树数据
      menuList: [],
      // 分类树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 分类状态数据字典
      statusOptions: [],
      //模型选项
      modelOptions: [],
      //单独所属模块选项
      moduleTypeOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      // 表单参数
      form: {icon: ''},
      // 表单校验
      rules: {
        menuName: [
          {required: true, message: "分类名称不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "分类编码称不能为空", trigger: "blur"}
        ],
        orderNum: [
          {required: true, message: "分类顺序不能为空", trigger: "blur"}
        ],
      }
    });

    onBeforeMount(()=>{
      getList();
    }) ;
    const {proxy} = getCurrentInstance() as any;
    // 选择图标
    const selected = (name: any) => {
      state.form.icon = name;
    };
    /** 查询分类列表 */
    const getList = () => {
      // getMenuList(state.queryParams).then(res=>{
      //   state.menuList = proxy.handleTree(res.data.rules??[], "id","pid");
      // })
      state.loading = true;
      listCateMenu(state.queryParams).then(response => {
        state.menuList = state.handleTree(response.data.list, "id", "pid");
        state.loading = false;
      });
    };
    /** 转换分类数据结构 */
    const normalizer = (node) => {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.title,
        children: node.children
      };
    };
    const getTreeselect = () => {
      treeselect().then(response => {
        const menus = []
        response.data.parentList.forEach(row => {
          if (row.pid === 0 && XEUtils.includes([100, 101], row.id)) {
            menus.push(row)
          }
          if (row.pid > 0 && row.menuType === 0) {
            menus.push(row)
          }
        })
        this.menuOptions = [];
        const menu = {id: 0, title: '主类目', children: []};
        menu.children = this.handleTree(menus, "id", "pid");
        this.menuOptions.push(menu);
      });
    };
    const visibleFormat = (row, column) => {
      if (row.menuType == "2") {
        return "";
      }
      return this.selectDictLabel(this.visibleOptions.values, row.alwaysShow);
    };
    const statusFormat = (row, column) => {
      if (row.menuType == "2") {
        return "";
      }
      return this.selectDictLabel(this.statusOptions.values, row.status);
    };
    const cancel = () => {
      this.open = false;
      this.reset();
    };
    const reset = () => {
      this.form = {
        menuId: undefined,
        parentId: 0,
        name: '',
        menuName: undefined,
        icon: undefined,
        menuType: "0",
        orderNum: "0",
        isFrame: "0",
        visible: "1",
        status: "1",
        path: '',
        jumpPath: '',
        component: '',
        moduleType: 'sys_admin',
        modelId: undefined,
      };
      this.resetForm("form");
    };
    const handleQuery = () => {
      this.getList();
    };
    const handleAdd = (row) => {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加分类";
    };
    const handleUpdate = (row) => {
      this.reset();
      getCategory(row.id).then(response => {
        const menus = []
        response.data.parentList.forEach(row => {
          if (row.pid === 0 && XEUtils.includes([100, 101], row.id)) {
            menus.push(row)
          }
          if (row.pid > 0 && row.menuType === 0) {
            menus.push(row)
          }
        })
        this.menuOptions = [];
        const menu = {id: 0, title: '主类目', children: []};
        menu.children = this.handleTree(menus, "id", "pid");
        this.menuOptions.push(menu);
        this.modelOptions = response.data.modelOptions
        const menuInfo = response.data.menu
        this.form = {
          menuId: menuInfo.id,
          parentId: menuInfo.pid,
          name: menuInfo.name,
          menuName: menuInfo.title,
          icon: menuInfo.icon,
          menuType: "" + menuInfo.menuType,
          orderNum: menuInfo.weigh,
          isFrame: "" + menuInfo.isFrame,
          visible: "" + menuInfo.alwaysShow,
          status: "" + menuInfo.status,
          path: menuInfo.path,
          jumpPath: menuInfo.jumpPath,
          component: menuInfo.component,
          moduleType: menuInfo.moduleType,
          modelId: menuInfo.modelId === 0 ? undefined : menuInfo.modelId
        }
        this.open = true;
        this.title = "修改分类";
      });
    };
    const submitForm = () => {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.menuId != undefined) {
            updateMenu(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            this.form.path = this.form.name
            addMenu(this.form).then(response => {
              if (response.code === 0) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    };
    const handleDelete = (row) => {
      this.$confirm('是否确认删除名称为"' + row.title + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delMenu(row.id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    };
    const changeModule = (module) => {
      this.form.modelId = undefined

      getModelOptions(module).then(response => {

        if (response.data) {
          this.modelOptions = response.data
        } else {
          this.modelOptions = []
        }
      })
    };
    return {
      selected,
      getList,
      normalizer,
      getTreeselect,
      visibleFormat,
      statusFormat,
      cancel,
      reset,
      handleQuery,
      handleAdd,
      handleUpdate,
      submitForm,
      handleDelete,
      changeModule,
      ...toRefs(state),
    };
  },

});
</script>
